package com.example.waimai.contraller;


import com.example.waimai.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.resource.HttpResource;

import java.io.*;
import java.net.http.HttpResponse;
import java.util.UUID;


@Slf4j
@Controller
@RestController
@RequestMapping("/common")
public class CommonContraller {

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        //得到原始名称
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        String filename = UUID.randomUUID().toString()+ substring;

        //如果文件夹不存在，就创建一个
        File dir= new File(basePath);
        if(!dir.exists()){
            dir.mkdir();
        }
        try {
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(filename);
    }

    @GetMapping("/download")
    public R<String> download(String name, HttpServletResponse response){
        try {
            FileInputStream fis=new FileInputStream(basePath+name);
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");
            byte[] bytes=new byte[1024];
            int len=0;
            while ((len=fis.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            fis.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
